using OfficeOpenXml;
using UserManagement.Models;

namespace UserManagement.Services;

public class ExcelExportService : IExcelExportService
{
    public byte[] ExportUsers(List<User> users)
    {
        using (var package = new ExcelPackage())
        {
            var worksheet = package.Workbook.Worksheets.Add("Users");

            // 设置标题行
            worksheet.Cells[1, 1].Value = "用户名";
            worksheet.Cells[1, 2].Value = "邮箱";
            worksheet.Cells[1, 3].Value = "创建时间";

            // 写入数据
            int row = 2;
            foreach (var user in users)
            {
                worksheet.Cells[row, 1].Value = user.Username;
                worksheet.Cells[row, 2].Value = user.Email;
                worksheet.Cells[row, 3].Value = user.CreateTime;
                worksheet.Cells[row, 3].Style.Numberformat.Format = "yyyy-mm-dd hh:mm:ss"; // 日期格式
                row++;
            }

            // 自动调整列宽
            worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
            return package.GetAsByteArray();
        }
    }
}